package com.example.demo.pdf.service;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.springframework.beans.factory.annotation.Value;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zjq
 * @version 创建时间：2022-4-2 14:40:55
 */
public class Pdfutil {

    //根据模板填充pdf数据的测试工具类---直接运行main方法

    // 模板路径
    @Value("${pdf-path}")
    private static String templatePath;

    // 利用模板生成pdf
    public static void pdfout(Map<String, Object> o) {

        // 生成的新文件路径
        String templatePath = "I:\\java\\1.pdf";
        String newPDFPath = "I:\\java\\testout.pdf";

        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {

            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            out = new FileOutputStream(newPDFPath);// 输出流
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            // 文字类的内容处理
            Map<String, String> datemap = (Map<String, String>) o.get("datemap");
            form.addSubstitutionFont(bf);
            for (String key : datemap.keySet()) {
                String value = datemap.get(key);
                form.setField(key, value);
            }

            Map<String, String> datemap2 = (Map<String, String>) o.get("datemap2");
            for (String key : datemap2.keySet()) {
                String value = datemap2.get(key);
                form.setField(key, value);
            }

            //图片类的内容处理
            Map<String,String> imgmap = (Map<String,String>)o.get("imgmap");
            for(String key : imgmap.keySet()) {
                String value = imgmap.get(key);
                String imgpath = value;
                int pageNo = form.getFieldPositions(key).get(0).page;
                Rectangle signRect = form.getFieldPositions(key).get(0).position;
                float x = signRect.getLeft();
                float y = signRect.getBottom();
                //根据路径读取图片
                Image image = Image.getInstance(imgpath);
                //获取图片页面
                PdfContentByte under = stamper.getOverContent(pageNo);
                //图片大小自适应
                image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                //添加图片
                image.setAbsolutePosition(x, y);
                under.addImage(image);
            }

            Map<String, String> datemap3 = (Map<String, String>) o.get("datemap3");
            for (String key : datemap3.keySet()) {
                String value = datemap3.get(key);
                form.setField(key, value);
            }

            stamper.setFormFlattening(true);// 如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();

            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            PdfImportedPage importPage2 = copy.getImportedPage(new PdfReader(bos.toByteArray()), 2);
            PdfImportedPage importPage3 = copy.getImportedPage(new PdfReader(bos.toByteArray()), 3);

            copy.addPage(importPage);
            copy.addPage(importPage2);
            copy.addPage(importPage3);
            doc.close();

        } catch (IOException e) {
            System.out.println(e);
        } catch (DocumentException e) {
            System.out.println(e);
        }

    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap();
        map.put("name", "张三");
        map.put("creatdate", "2018年1月1日");
        map.put("weather", "晴朗");

        Map<String, String> map2 = new HashMap();
        map2.put("a", "晴朗第二页");

        Map<String,String> imgmap = new HashMap();
        imgmap.put("img","I:/java/xing.jpg");
        imgmap.put("img2","I:/java/11.jpg");

        Map<String, String> map3 = new HashMap();
        map3.put("b", "晴朗第三页");

        Map<String, Object> o = new HashMap();
        o.put("datemap", map);
        o.put("datemap2", map2);
        o.put("imgmap", imgmap);
        o.put("datemap3", map3);
        pdfout(o);
    }
}
